package com.miplus.ccrm.core.service.crd;

import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.miplus.ccrm.common.EnumRCode;
import com.miplus.ccrm.common.JPubUtils;
import com.miplus.ccrm.common.ServiceException;
import com.miplus.ccrm.core.controller.vo.credit.CrdBillTailResVo;
import com.miplus.ccrm.core.controller.vo.credit.CrdCmdResVo;
import com.miplus.ccrm.core.utils.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.core.env.Environment;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Slf4j
public class CrdCommand {

    private static CrdCmdResVo doCommond(String appCode,String cmdurl,String requestBody) {
        return doCommond(appCode,cmdurl,requestBody,null);
    }
    /**
     * 与行内核心系统交互命令
     */
    private static CrdCmdResVo doCommond(String appCode,String cmdurl,String requestBody,String cardNo) {
        log.info("Commond({}):{}", cmdurl, requestBody);

        CrdCmdResVo resVo=new CrdCmdResVo();
        try{
            // 发送 POST 请求
            HttpResponse<JsonNode> jsonResponse = Unirest.post(cmdurl)
                    .header("Content-Type", "application/json;charset=UTF-8")
                    .body(requestBody)
                    .asJson();

            // 获取响应体
            int status = jsonResponse.getStatus();
            if (status == 200) {
                JsonNode responseBody = jsonResponse.getBody();
                log.info("Commond.Response:{}", responseBody);

                String xmlBody = responseBody.getObject().get("body").toString();

                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document doc=builder.parse(new InputSource(new StringReader(xmlBody)));

                String code = doc.getElementsByTagName("StatusCode").item(0).getTextContent();
                //String type = doc.getElementsByTagName("StatusType").item(0).getTextContent();
                String des = doc.getElementsByTagName("StatusDescription").item(0).getTextContent();

                if(JPubUtils.IsEqual(code,"0")&&JPubUtils.IsEqual(appCode,"DJKC0046")) {
                    //取出催信息
                    String cardQuery = responseBody.getObject().getJSONObject("filesMap").getString("CardQuery");
                    // 解码 Base64 字符串
                    byte[] decodedBytes = Base64.decodeBase64(cardQuery);
                    String decodedString = new String(decodedBytes, Charset.forName("GB18030"));
                    log.info("Commond.DJKC0046 decodedString(len={}):{}",decodedString.length(),decodedString);

                    String cardSource = doc.getElementsByTagName("card_source").item(0).getTextContent();
                    // 0=通联，1=银数
                    resVo=BuildAccBalance(cardSource,decodedString,cardNo);
                }else if(JPubUtils.IsEqual(code,"0")&&JPubUtils.IsEqual(appCode,"CREDQ001")) {
                    //取借记卡余额信息
                    //byte[] gb18030_body = xmlBody.getBytes(Charset.forName("GB18030"));
                    //xmlBody = new String(gb18030_body, Charset.forName("GB18030"));
                    //log.info("Commond.Body:{}", xmlBody);
                    // dsc为交易结果 如：<StatusDescription>卡片状态正常，解挂处理无效</StatusDescription>)
                    resVo.setBalance(doc.getElementsByTagName("balance").item(0).getTextContent());
                    resVo.setLastBalance(doc.getElementsByTagName("last_balance").item(0).getTextContent());
                }
                else if(JPubUtils.IsEqual(code,"0")&&JPubUtils.IsEqual(appCode,"CCFN3053")) {
                    //取银数逾期期数
                    String creditCardIB2 = responseBody.getObject().getJSONObject("filesMap").getString("CreditCardIB2");
                    byte[] decodedBytes = Base64.decodeBase64(creditCardIB2);
                    // 使用 GB18030 编码创建字符串
                    String decodedString = new String(decodedBytes, Charset.forName("GB18030"));
                    log.info("Commond.CCFN3053 decodedString:" + decodedString);

                    // 分割decodedString
                    String[] parts = decodedString.split("\\|");
                    log.info("CCFN3053.split(count={})：{}",parts.length,parts);

                    resVo.setMthsOdue(JPubUtils.StringToInt(parts[36]));
                }
                else if(JPubUtils.IsEqual(code,"0")&&JPubUtils.IsEqual(appCode,"DJKF0017")) {
                    //银数未出账账单明细
                    String cardQuery = responseBody.getObject().getJSONObject("filesMap").getString("CardBillDetail");
                    byte[] decodedBytes = Base64.decodeBase64(cardQuery);
                    String decodedString = new String(decodedBytes, Charset.forName("GB18030"));
                    log.info("Commond.DJKF0017 decodedString:" + decodedString);

                    ArrayList vallines=BuildLines(decodedString,"\\n",0);
                    List<CrdBillTailResVo> ll=BuildBillTail(appCode,vallines);
                    resVo.setBillTailList(ll);
                }
                else if(JPubUtils.IsEqual(code,"0")&&JPubUtils.IsEqual(appCode,"DJKG0005")) {
                    //通联未出账账单明细DJKF0005
                    String cardQuery = responseBody.getObject().getJSONObject("filesMap").getString("DJKG00051");
                    byte[] decodedBytes = Base64.decodeBase64(cardQuery);
                    String decodedString = new String(decodedBytes, Charset.forName("GB18030"));
                    log.info("Commond.DJKG0005 decodedString:" + decodedString);
                    String totalRows = doc.getElementsByTagName("total_rows").item( 0).getTextContent();
                    String nextpagflag="N";
                    if(JPubUtils.StringToInt(totalRows)>0) {
                        nextpagflag=doc.getElementsByTagName("nextpage_flg").item(0).getTextContent();
                    }
                    log.info("Commond.DJKG0005:totalRows={},nextpagflag={}", totalRows,nextpagflag);
                    ArrayList vallines=BuildLines(decodedString,"\\n",3);
                    List<CrdBillTailResVo> ll=BuildBillTail(appCode,vallines);
                    resVo.setNextpageflg(nextpagflag);
                    resVo.setBillTailList(ll);
                }
                else if(JPubUtils.IsEqual(code,"0")&&JPubUtils.IsEqual(appCode,"DJKG0004")) {
                    //通联未入账账单明细DJKF0004
                    String cardQuery = responseBody.getObject().getJSONObject("filesMap").getString("DJKG00041");
                    byte[] decodedBytes = Base64.decodeBase64(cardQuery);
                    String decodedString = new String(decodedBytes, Charset.forName("GB18030"));
                    log.info("Commond.DJKG0004 decodedString:" + decodedString);

                    ArrayList vallines=BuildLines(decodedString,"\\n",3);
                    List<CrdBillTailResVo> ll=BuildBillTail(appCode,vallines);
                    resVo.setBillTailList(ll);
                }

                log.info("Commond.code={},des={}", code, des);

                if(JPubUtils.IsEqual(code,"0")) {
                    resVo.setRespCode(code);
                    resVo.setRespCodeDesc("Success");
                }
                else{
                    resVo.setRespCode(code);
                    resVo.setRespCodeDesc("Fail:" + des + "(" + code + ")");
                }
            }
            else{
                resVo.setRespCode(String.format("%d",EnumRCode.CrdCmdFail.value));
                resVo.setRespCodeDesc("接口指令网络Error："+String.format("%d",status));
            }
        }
        catch (Exception e){
            log.warn("doCommond:",e);
            resVo.setRespCode(String.format("%d",EnumRCode.CrdCmdFail.value));
            resVo.setRespCodeDesc("接口指令异常："+e.getMessage());
        }

        return resVo;
    }

    private static ArrayList BuildLines(String decodedString, String regex,int pos)
    {
        // 分割decodedString,// 去掉pos行
        String[] lines = decodedString.split(regex);
        log.info("BuildLines.split(count={})：{}",lines.length,lines);
        ArrayList vallines=new ArrayList();
        for (int i = pos; i < lines.length; i++) {
            vallines.add(lines[i]);
        }
        return vallines;
    }

    private static List<CrdBillTailResVo> BuildBillTail(String appCode,ArrayList vallines)
    {// . 、 $、 | 和 * 等转义字符，必须得加 \\
        List<CrdBillTailResVo> bills=new ArrayList<>();
        for(int i=0;i<vallines.size();i++){
            String line=vallines.get(i).toString();
            if(line.length()<10) continue;
            CrdBillTailResVo bill=new CrdBillTailResVo();
            String[] parts=line.split("\\|");
            log.info("BuildBillTail({}).split(count={}):{}",appCode,parts.length,parts);
            if(parts.length<18) continue;
            if (JPubUtils.IsEqual(appCode, "DJKF0017")) {//银数
                bill.setInpDate(parts[0]); //交易日期
                bill.setInpTime(parts[1]); //交易时间
                bill.setValDate(parts[2]);//记账日期
                //国内国外标识[3],交易国籍[4],一级商户名称[5],二级商户名称[6]
                bill.setDesLine1(parts[5]);
                bill.setDesLine2(parts[6]);
                bill.setCardNo(parts[7]);//卡号后四位
                bill.setMerCatCd(parts[8]); //商户类型
                bill.setTransTypeName(parts[9]); //交易类型名称
                bill.setCurrncyCd(parts[10]);//记账币种
                bill.setBillAmt(new BigDecimal(parts[11].trim())); //记账币种金额
                bill.setOrgnCurr(parts[12]);
                bill.setOrgnAmt(new BigDecimal(parts[13].trim()));
                bill.setXtranno(parts[16]); //交易流水号
                //交易金额符号[17]
                //bill.setAuthCode(parts[17]);
                bill.setDbCrInd(parts[17]);
                bill.setTransType(parts[19]); //交易类型
                //3171(加工ing_6月上线)---- DJKFO017 商户编号收单
            } else if (JPubUtils.IsEqual(appCode, "DJKG0005")) {
                bill.setCardNo(parts[0]);
                bill.setInpDate(parts[1]);
                bill.setInpTime(parts[2]);
                bill.setTransType(parts[3]); //交易类型
                bill.setTransTypeName(parts[4]); //交易类型描述
                //交易码 parts[3] 交易码简要描述parts[4] 不需要，
                bill.setOrgnAmt(new BigDecimal(parts[5].trim())); //交易金额
                bill.setBillAmt(new BigDecimal(parts[6].trim())); //入账币种金额
                bill.setCurrncyCd(parts[7]);//入账币种
                bill.setValDate(parts[8]);//val_date
                bill.setAuthCode(parts[9]);
                bill.setOrgnCurr(parts[10]);//交易币种代码 parts[9]
                bill.setXtranno(parts[11]); //交易参考号
                //bill.setDesLine1(parts[11]); //账单交易描述
                //受卡方标识码[12],受理机构名称地址[13
                //借贷标志[15],
                //是否超限[17],入账逻辑模块[18],信用计划类型[19],信用计划模板号[20],信用计划模板描述[21],结算币种[22],
                //结算金额[23],商户类型描述[24]
                bill.setDesLine1(parts[12]);
                bill.setMerchant(parts[13]);//商户编号收单
                bill.setDesLine2(parts[14]);
                bill.setDbCrInd(parts[16]);
                bill.setMerCatCd(parts[17]); //商户类型
            }
            else if (JPubUtils.IsEqual(appCode, "DJKG0004")) { //通联未入账明细
                bill.setCardNo(parts[0]);
                //parts[1]
                if(JPubUtils.IsNotEmpty(parts[2])) {
                    bill.setOrgnAmt(new BigDecimal(parts[2].trim())); //交易金额
                }
                bill.setOrgnCurr(parts[3]);//交易币种代码
                bill.setAuthCode(parts[4]); //授权码
                bill.setDesLine2(parts[5]);
                if(JPubUtils.IsNotEmpty(parts[6])) {
                    bill.setBillAmt(new BigDecimal(parts[6].trim())); //入账币种金额
                }
                //parts[7] //交易渠道
                //parts[8] //终端类型
                bill.setMerCatCd(parts[9]); //商户类型代码
                //parts[10] //交易方向
                //parts[11] //交易状态
                bill.setTransType(parts[12]); //交易类型
                //parts[13] //联机日期
                //parts[14] //联机时间
                //parts[15] //联机业务日期
                //parts[16]); //交易类型标志
                //parts[17] //人工授权标志
                //parts[18] //最终行动
                //parts[19] //支付密码错误次数
                //parts[20] //返回码-B039
                //parts[21] //是否境外交易
                //parts[22] //交易介质

                bill.setInpDate(parts[23]); //授权请求日期
                bill.setInpTime(parts[24]);  //授权请求时间
                //parts[25] 商户国家代码-B019
                //parts[26] 受理机构标识码
                //parts[27] 受卡机的终端标识码-B041
                bill.setMerchant(parts[28]); //parts[28] 受卡方(商户)标识码-B042
                 //parts[29] 系统跟踪号-B011
                //parts[30] 交易传输时间-B007
                //parts[31] 服务点 PIN 获取码-B022
                //parts[32] 服务点条件码-B025
                //parts[33] 自定义域-B060
                bill.setXtranno(parts[33]);//parts[34] 检索参考号-B037
                //parts[35] 创建操作员 ID
                //parts[36] 授权原因
                //parts[37] 授权原因描述

                bill.setCurrncyCd(parts[38]);//入账币种
                //拒绝原因=39
                //银联贷记标识=40
                //资金来源=41
                //对方名称=42
                //对方卡号=43
                bill.setDesLine1(parts[44]);
                //对方账号=45
                //可用额度=46
                //场景渠道=47
                //交易介质=48
                //二维码场景标识=49
                //交易国别=50
                //境内外标示=51
                //交易渠道=52
                //商户分类=53
                bill.setTransTypeName(parts[54]); //交易类型描述
            }
            log.info("BuildBillTail:{}",bill);
            bills.add(bill);
        }
        return bills;
    }

    public static String getCrdCommandUrl()
    {
        Environment environment = (Environment) SpringContextUtil.getBean("environment");
        String cmdurl = environment.getProperty("credit.command.url");
        if (JPubUtils.IsEmpty(cmdurl)) {
            throw new ServiceException(EnumRCode.NoFindConfig.value, EnumRCode.NoFindConfig.name);
        }
        return cmdurl;
    }

    //判定出催，达成
    public static CrdCmdResVo BuildAccBalance(String cardSource,String decodedString,String cardNo)
    {//cardSource：0=通联(美团)，1=银数
        CrdCmdResVo resVo=new CrdCmdResVo();
        resVo.setIsRpc(0);
        if (JPubUtils.IsEqual(cardSource, "0")) {
            ArrayList vallines=BuildLines(decodedString,"\\n",3);
            if(vallines.size()<=0){
                throw new ServiceException(EnumRCode.CrdRespFmErr.value, EnumRCode.CrdRespFmErr.name);
            }
            String fourthLine = vallines.get(0).toString();
            String[] parts = fourthLine.split("\\|");
            log.info("BuildAccBalance(MT).split(count={})：{}",parts.length,parts);
            if(parts.length<83){
                throw new ServiceException(EnumRCode.CrdRespFmErr.value, EnumRCode.CrdRespFmErr.name);
            }
            // 通联 逾期期数(parts[50])、最小还款额(parts[83])、已出账单欠款（当前余额（parts[26]））、还款未入账金额交易（parts[53]）
            //System.out.println("50:" + parts[50] + "  83:" + parts[83] + "  26:" + parts[26] + "  53:" + parts[53]);
            resVo.setLowestRepayBal(new BigDecimal(parts[83].trim()));
            resVo.setSettledBillAmt(new BigDecimal(parts[35].trim())); //以前取26，现在改成35
            resVo.setUnbillPaymt(new BigDecimal(parts[53].trim()));
            int odue=JPubUtils.StringToInt(parts[50].trim());
            if(odue<9) {
                odue--;
                if (odue < 0) odue = 0;
                resVo.setMthsOdue(odue);
            }else{
                resVo.setMthsOdue(-1);
            }
            BigDecimal lowestRepayBal=resVo.getLowestRepayBal();
            log.info("BuildAccBalance(MT):lowestRepayBal={},settledBillAmt={},unbillPaymt={},parts[50]={},mthsOdue={}",
                    lowestRepayBal,resVo.getSettledBillAmt(),resVo.getUnbillPaymt(),parts[50],resVo.getMthsOdue()
            );
            //if (JPubUtils.StringToInt(parts[50])==0 && lowestRepayBal.compareTo(BigDecimal.ZERO)<=0) {
            if (odue<=0) { //只判定逾期期数,2024-05-28
                resVo.setIsRpc(1);
            }
        } else {
            String gbkString="";
            byte[] gbkBytes=null;
            try {
                gbkBytes = decodedString.getBytes("GBK");
                //gbkString=new String(gbkBytes);
            }catch (Exception e){
                log.warn("gbkString.Err:{}",e.getMessage());
                throw new ServiceException(EnumRCode.CrdRespFmErr.value, EnumRCode.CrdRespFmErr.name);
            }
            log.info("gbkString(len={}):{}",gbkBytes.length,gbkString);
            // 最低还款额1=银数
            //String lowestRepayBal = decodedString.substring(1491, 1491 + 12);
            //已出账单欠款（当前余额）
            //resVo.setSettledBillAmt(getCrdBillAmt(gbkString,434,12,446));
            resVo.setSettledBillAmt(getCrdBillAmt(gbkBytes,434,12,446));
            //未出账单欠款
            //resVo.setUnsettledBillAmt(getCrdBillAmt(gbkString,879,12,891));
            resVo.setUnsettledBillAmt(getCrdBillAmt(gbkBytes,879,12,891));
            //最低还款额
            //resVo.setLowestRepayBal(getCrdBillAmt(gbkString,705,12,0));
            resVo.setLowestRepayBal(getCrdBillAmt(gbkBytes,705,12,0));
            //利息
            //resVo.setInterestFee(getCrdBillAmt(gbkString,1407,11,0));
            resVo.setInterestFee(getCrdBillAmt(gbkBytes,1407,11,0));
            //违约金
            //resVo.setPenchgAcc(getCrdBillAmt(gbkString,826,12,0));
            resVo.setPenchgAcc(getCrdBillAmt(gbkBytes,826,12,0));
            //其他费用
            //BigDecimal oth825=getCrdBillAmt(gbkString,1034,12,0);
            BigDecimal oth825=getCrdBillAmt(gbkBytes,1034,12,0);
            resVo.setOthExpense(oth825.subtract(resVo.getPenchgAcc()));
            //应收透支利息
            //resVo.setIntChgd(getCrdBillAmt(gbkString,777,12,0));
            resVo.setIntChgd(getCrdBillAmt(gbkBytes,777,12,0));
            //还款金额
            //resVo.setPaymtClrd(getCrdBillAmt(gbkString,293,12,0));
            resVo.setPaymtClrd(getCrdBillAmt(gbkBytes,293,12,0));
            //逾期金额
            //resVo.setAge1Age6(getCrdBillAmt(gbkString,305,12,0));
            resVo.setAge1Age6(getCrdBillAmt(gbkBytes,305,12,0));
            //总欠款
            //resVo.setAcctDebtAll(getCrdBillAmt(gbkString,2006,11,2017));
            resVo.setAcctDebtAll(getCrdBillAmt(gbkBytes,2006,11,2017));
            BigDecimal lowestRepayBal=resVo.getLowestRepayBal();
            Integer mthsOdue = yinShuAcct(cardNo);
            log.info("BuildAccBalance(YS):mthsOdue={},lowestRepayBal={}",mthsOdue,lowestRepayBal);
            //mthsOdue--; //不再减1,2024-06-04
            if(mthsOdue<0) mthsOdue=0;
            resVo.setMthsOdue(mthsOdue);
            //if (mthsOdue <= 0 && lowestRepayBal.compareTo(BigDecimal.ZERO)<=0) {
            if (mthsOdue <= 0) { //只判定逾期期数,2024-05-28
                resVo.setIsRpc(1);
            }
        }

        return resVo;
    }

    private static BigDecimal getCrdBillAmt(String decodedString,int startpos,int len,int flagpos)
    {
        String s=decodedString.substring(startpos, startpos + len);
        String s1=s.substring(0,s.length()-2)+"."+s.substring(s.length()-2);
        String flag="+";
        if(flagpos>0){
            flag=decodedString.substring(flagpos, flagpos+1);
        }
        if(JPubUtils.IsEqual(flag,"-")){
            s1=flag+s1;
        }
        log.info("getCrdBillAmt:startpos={},len={},flagpos={}=>{}",startpos,len,flagpos,s1);
        BigDecimal decimal=new BigDecimal(s1);

        log.info("getCrdBillAmt:{}",decimal);

        return decimal;
    }

    private static BigDecimal getCrdBillAmt(byte[] gbkBytes,int startpos,int len,int flagpos)
    {
        byte[] bytes=new byte[len];
        Arrays.fill(bytes,(byte)0);
        System.arraycopy(gbkBytes,startpos,bytes,0,len);
        String s=new String(bytes);
        String s1=s.substring(0,s.length()-2)+"."+s.substring(s.length()-2);
        String flag="+";
        if(flagpos>0){
            //decodedString.substring(flagpos, flagpos+1);
            flag=Byte.toString(gbkBytes[flagpos]);
        }
        if(JPubUtils.IsEqual(flag,"-")){
            s1=flag+s1;
        }
        log.info("getCrdBillAmt:startpos={},len={},flagpos={},flag={}>>>{}",startpos,len,flagpos,flag,s1);
        BigDecimal decimal=new BigDecimal(s1);

        log.info("getCrdBillAmt:{}",decimal);

        return decimal;
    }

    /**
     * 账户管控命令 DJKB0018
     */
    public static CrdCmdResVo crdCardFrozen(String cardno,String opt,String crdsts,String crdorg) {
        //卡管制或解管制,opt=0:管控;1:解管控
        //sts=S, 锁定码(必填)待提供字典
        //org=1,  0:账户层;1:卡片层
        String cmdurl = getCrdCommandUrl();

        String sts="S",org="0";
        if(JPubUtils.IsNotEmpty(crdsts)){
            sts=crdsts;
        }
        if(JPubUtils.IsNotEmpty(crdorg)){
            org=crdorg;
        }

        String requestBody = "{\n" +
                "  \"body\": \"<?xml version=\\\"1.0\\\" encoding=\\\"GB18030\\\"?>\\n<hzbank xmlns=\\\"http://www.hzbank.com.cn/ib2service/DJKB0018/\\\">\\n<RequestHeader>\\n<SysReqHeader>\\n<TransactionRef>0000</TransactionRef>\\n<BranchNo>02</BranchNo>\\n<SourceChannel>23</SourceChannel>\\n<Language>0001</Language>\\n<VersionNo>1</VersionNo>\\n<TerminalNo>0000</TerminalNo>\\n<SystemType></SystemType>\\n<OperatorId>EBK001</OperatorId>\\n<SessionToken></SessionToken>\\n<SenderNode>0000</SenderNode>\\n<SenderServer>%s</SenderServer>\\n<SenderJournalNo>%s</SenderJournalNo>\\n<SenderDate>%s</SenderDate>\\n<SenderTime>%s</SenderTime>\\n<TransferNode></TransferNode>\\n<TransferServer></TransferServer>\\n<TransferJournalNo></TransferJournalNo>\\n<TransferDate>%s</TransferDate>\\n<TransferTime>%s</TransferTime>\\n</SysReqHeader>\\n<TxnReqHeader>\\n<MessageType>0000</MessageType>\\n<TransactionCode>%s</TransactionCode>\\n<SecondStamp>0000</SecondStamp>\\n<AuthorOperatorId>0000</AuthorOperatorId>\\n<AuthorFingerprint>0000</AuthorFingerprint>\\n<AuthorPassword>0000</AuthorPassword>\\n<CheckOperatorId>0000</CheckOperatorId>\\n<RelatedCycleNo>0000</RelatedCycleNo>\\n<RelatedAccDate></RelatedAccDate>\\n<Reserve>0000</Reserve>\\n</TxnReqHeader>\\n</RequestHeader>\\n<RequestBody>\\n<Card_Manager>\\n<card_no>%s</card_no>\\n<opt>%s</opt>\\n<sts>%s</sts>\\n<org>%s</org>\\n</Card_Manager>\\n</RequestBody>\\n</hzbank>\",\n" +
                "  \"appCode\": \"DJKB0018\",\n" +
                "  \"type\": \"json\",\n" +
                "  \"toSys\": \"crd_serv\"\n" +
                "}";
        LocalDateTime currentDateTime = LocalDateTime.now();
        // 定义占位符变量的值
        String senderServer = "CCRM",
                senderJournalNo = currentDateTime.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")),
                senderDate = currentDateTime.format(DateTimeFormatter.ofPattern("yyyyMMdd")),
                senderTime = currentDateTime.format(DateTimeFormatter.ofPattern("HHmmss")),
                transferDate = currentDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
                transferTime = currentDateTime.format(DateTimeFormatter.ofPattern("HH:mm:ss")),
                transactionCode = "DJKB0018";

        // 使用占位符变量替换 XML 字符串中的占位符
        requestBody = String.format(requestBody,
                senderServer, senderJournalNo, senderDate, senderTime,
                transferDate, transferTime, transactionCode,
                cardno, opt, sts, org
        );

        cmdurl=cmdurl+"/Card_Manager";

        return doCommond("DJKB0018",cmdurl,requestBody);
    }

    /**
     * 账户划扣命令 CRED1042
     */
    public static CrdCmdResVo crdCarDeduction(String cardno,String crdcardno,BigDecimal amount) {
        //划扣:从借记卡划cardno扣到信用卡crdcardno
        String cmdurl = getCrdCommandUrl();
        String requestBody = "{\n" +
                "  \"body\": \"<?xml version=\\\"1.0\\\" encoding=\\\"GB18030\\\"?>\\n<hzbank xmlns=\\\"http://www.hzbank.com.cn/ib2service/CRED1042/\\\">\\n<RequestHeader>\\n<SysReqHeader>\\n<SourceChannel>0509</SourceChannel>\\n<BranchNo>7515</BranchNo>\\n<OperatorId>CREDIT</OperatorId>\\n<SenderJournalNo>%s</SenderJournalNo>\\n<SenderDate>%s</SenderDate>\\n<SenderTime>%s</SenderTime>\\n</SysReqHeader>\\n<TxnReqHeader>\\n<TransactionCode>%s</TransactionCode>\\n<SecondStamp>0</SecondStamp>\\n<RelatedCycleNo>0</RelatedCycleNo>\\n</TxnReqHeader>\\n</RequestHeader>\\n<RequestBody>\\n<ISO8583_Business>\\n<FTH2G_2_primary_account_number>%s</FTH2G_2_primary_account_number>\\n<FTH2G_4_amount_of_transactions>%s</FTH2G_4_amount_of_transactions>\\n<FTH2G_42_card_acceptor_id_code>999999999999924</FTH2G_42_card_acceptor_id_code>\\n<FTH2G_7_transmission_date_and_time>%s</FTH2G_7_transmission_date_and_time>\\n<FTH2G_75_reversal_number_of_credits>0</FTH2G_75_reversal_number_of_credits>\\n<FTH2G_76_number_of_debits>0</FTH2G_76_number_of_debits>\\n<FTH2G_77_reversal_number_of_debits>0</FTH2G_77_reversal_number_of_debits>\\n<FTH2G_78_number_of_transfer>0</FTH2G_78_number_of_transfer>\\n<FTH2G_79_reversal_number_of_transfer>0</FTH2G_79_reversal_number_of_transfer>\\n<FTH2G_80_number_of_inquiries>0</FTH2G_80_number_of_inquiries>\\n<FTH2G_81_number_of_authorizations>0</FTH2G_81_number_of_authorizations>\\n <FTH2G_102_account_id_1>%s</FTH2G_102_account_id_1>\\n</ISO8583_Business>\\n</RequestBody>\\n</hzbank>\",\n" +
                "  \"appCode\": \"CRED1042\",\n" +
                "  \"type\": \"json\",\n" +
                "  \"toSys\": \"0000\"\n" +
                "}";
        LocalDateTime currentDateTime = LocalDateTime.now();
        // 定义占位符变量的值
        String senderJournalNo = currentDateTime.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")),
                senderDate = currentDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
                senderTime = currentDateTime.format(DateTimeFormatter.ofPattern("HH:mm:ss")),
                transactionCode = "CRED1042",
                transmissionDateTime = currentDateTime.format(DateTimeFormatter.ofPattern("MMddHHmmss"));//交易时间（非必填） MMDDhhmmss

        // 使用占位符变量替换 XML 字符串中的占位符
        requestBody = String.format(requestBody,
                senderJournalNo, senderDate, senderTime, transactionCode,
                crdcardno, amount.toString(), transmissionDateTime, cardno);

        cmdurl=cmdurl+"/ISO8583_Business";

        return doCommond("CRED1042",cmdurl,requestBody);
    }

    /**
     * 借记卡信息余额 CREDQ001
     */
    public static CrdCmdResVo crdAcctBalance(String acctno) {
        String cmdurl = getCrdCommandUrl();
        String requestBody = "{\n" +
                "  \"body\": \"<?xml version=\\\"1.0\\\" encoding=\\\"GB18030\\\"?>\\n<hzbank xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xmlns:xsd=\\\"http://www.w3.org/2001/XMLSchema\\\" xmlns=\\\"http://www.hzbank.com.cn/ibservice/CREDQ001/\\\">\\n  <RequestHeader>\\n<SysReqHeader>\\n<TransactionRef>%s</TransactionRef>\\n<BranchNo>7571</BranchNo>\\n<SourceChannel>9998</SourceChannel>\\n      <Language>0001</Language>\\n      <VersionNo>1.1</VersionNo>\\n      <TerminalNo>8865473</TerminalNo>\\n      <SystemType>CO</SystemType>\\n      <OperatorId>310011</OperatorId>\\n      <SessionToken>kCpnd0w05JBlBJuyYpbdPXUUKmpoRc7P2AVQY9YZGZVAKRm5DDR8EqgtYjj7V0MBvp6Recfz4e1PDcOhUr/oaKuJFQIE/vn5WGq9cow/6shZMUw4U1VRNVhKUktRMDJC</SessionToken>\\n  <SenderNode>324</SenderNode>\\n <SenderServer>%s</SenderServer>\\n      <SenderJournalNo>%s</SenderJournalNo>\\n      <SenderDate>%s</SenderDate>\\n      <SenderTime>%s</SenderTime>\\n      <TransferNode />\\n      <TransferServer />\\n      <TransferJournalNo />\\n      <TransferDate />\\n      <TransferTime />\\n    </SysReqHeader>\\n    <TxnReqHeader>\\n      <MessageType>0000</MessageType>\\n      <TransactionCode>%s</TransactionCode>\\n      <RelatedCycleNo>1</RelatedCycleNo>\\n      <RelatedAccDate>%s</RelatedAccDate>\\n    </TxnReqHeader>\\n  </RequestHeader>\\n  <RequestBody>\\n    <Custservice_Call>\\n        <pay_acc>%s</pay_acc>\\n    </Custservice_Call>\\n  </RequestBody>\\n</hzbank>\",\n" +
                "  \"appCode\": \"CREDQ001\",\n" +
                "  \"type\": \"json\",\n" +
                "  \"toSys\": \"0000\"\n" +
                "}";
        LocalDateTime currentDateTime = LocalDateTime.now();
        // 定义占位符变量的值
        String transactionRef = currentDateTime.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")),
                senderServer = "CCRM",
                senderJournalNo = currentDateTime.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")),
                senderDate = currentDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
                senderTime = currentDateTime.format(DateTimeFormatter.ofPattern("HH:mm:ss")),
                transactionCode = "CREDQ001",
                relatedAccDate = currentDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
                payAcc = acctno; //账号（必填）

        // 使用占位符变量替换 XML 字符串中的占位符
        requestBody = String.format(requestBody, transactionRef, senderServer, senderJournalNo,
                senderDate, senderTime, transactionCode, relatedAccDate, payAcc);

        cmdurl=cmdurl+"/Custservice_Call";

        return doCommond("CREDQ001",cmdurl,requestBody);
    }

    /**
     * 账户信息查询（信用卡）DJKC0046 出催
     */
    public static CrdCmdResVo cardAcctBusiness(String custId,String cardNo,String currCd)
    {
        String cmdurl = getCrdCommandUrl();
        // 设置请求体
        String requestBody = "{\n" +
                "  \"body\": \"<?xml version=\\\"1.0\\\" encoding=\\\"GB18030\\\"?>\\n<hzbank xmlns=\\\"http://www.hzbank.com.cn/ib2service/DJKC0046/\\\">\\n  <RequestHeader>\\n    <SysReqHeader>\\n      <TransactionRef>0000</TransactionRef>\\n      <BranchNo>02</BranchNo>\\n      <SourceChannel>23</SourceChannel>\\n      <Language>0001</Language>\\n      <VersionNo>1</VersionNo>\\n      <TerminalNo>0000</TerminalNo>\\n      <SystemType></SystemType>\\n      <OperatorId>EBK001</OperatorId>\\n      <SessionToken></SessionToken>\\n      <SenderNode>0000</SenderNode>\\n      <SenderServer>%s</SenderServer>\\n      <SenderJournalNo>%s</SenderJournalNo>\\n      <SenderDate>%s</SenderDate>\\n      <SenderTime>%s</SenderTime>\\n      <TransferNode></TransferNode>\\n      <TransferServer></TransferServer>\\n      <TransferJournalNo></TransferJournalNo>\\n      <TransferDate>%s</TransferDate>\\n      <TransferTime>%s</TransferTime>\\n    </SysReqHeader>\\n    <TxnReqHeader>\\n      <MessageType>0000</MessageType>\\n      <TransactionCode>%s</TransactionCode>\\n      <SecondStamp>0000</SecondStamp>\\n      <AuthorOperatorId>0000</AuthorOperatorId>\\n      <AuthorFingerprint>0000</AuthorFingerprint>\\n      <AuthorPassword>0000</AuthorPassword>\\n      <CheckOperatorId>0000</CheckOperatorId>\\n      <RelatedCycleNo>0000</RelatedCycleNo>\\n      <RelatedAccDate></RelatedAccDate>\\n      <Reserve>0000</Reserve>\\n    </TxnReqHeader>\\n  </RequestHeader>\\n  <RequestBody>\\n\\t<CardAcct_Business>\\n\\t\\t<card_no>%s</card_no>\\n\\t\\t<id_type></id_type>\\n\\t\\t<id_no></id_no>\\n\\t\\t<curr_cd>%s</curr_cd>\\n\\t\\t<firstrow>%s</firstrow>\\n\\t\\t<lastrow>%s</lastrow>\\n\\t\\t<cust_id>%s</cust_id>\\n\\t\\t<user_flag>%s</user_flag>\\n\\t</CardAcct_Business>\\n</RequestBody>\\n</hzbank>\",\n" +
                "  \"appCode\": \"DJKC0046\",\n" +
                "  \"type\": \"json\",\n" +
                "  \"toSys\": \"crd_serv\"\n" +
                "}";
        if(JPubUtils.IsEmpty(currCd)){
            currCd="156";   //币种=人民币
        }

        // 获取当前日期和时间
        LocalDateTime currentDateTime = LocalDateTime.now();

        // 定义占位符变量的值
        String senderServer = "CCRM",
                senderJournalNo = currentDateTime.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")),
                senderDate = currentDateTime.format(DateTimeFormatter.ofPattern("yyyyMMdd")),
                senderTime = currentDateTime.format(DateTimeFormatter.ofPattern("HHmmss")),
                transferDate = currentDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
                transferTime = currentDateTime.format(DateTimeFormatter.ofPattern("HH:mm:ss")),
                transactionCode = "DJKC0046",
                firstrow = "0",   //开始位置
                lastrow = "9",    //结束位置
                userFlag = "L";  //强弱用户标识

        // 使用占位符变量替换 XML 字符串中的占位符
        requestBody = String.format(requestBody, senderServer, senderJournalNo, senderDate, senderTime, transferDate,
                transferTime, transactionCode, cardNo, currCd, firstrow, lastrow, custId, userFlag);

        cmdurl=cmdurl+"/CardAcct_Business";

        return doCommond("DJKC0046",cmdurl,requestBody,cardNo);
    }

    /**
     * 获取银数逾期期数CCFN3053
     */
    private static Integer yinShuAcct(String cardNo) {

        String requestBody = "{\n" +
                "  \"body\": \"<?xml version=\\\"1.0\\\" encoding=\\\"GB18030\\\"?>\\n<hzbank xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xmlns:xsd=\\\"http://www.w3.org/2001/XMLSchema\\\" xmlns=\\\"http://www.hzbank.com.cn/ibservice/CCFN3053/\\\">\\n  <RequestHeader>\\n    <SysReqHeader>\\n      <TransactionRef>%s</TransactionRef>\\n      <BranchNo>7571</BranchNo>\\n      <SourceChannel>9998</SourceChannel>\\n      <Language>0001</Language>\\n      <VersionNo>1.1</VersionNo>\\n      <TerminalNo>8865473</TerminalNo>\\n      <SystemType>CO</SystemType>\\n      <OperatorId>310011</OperatorId>\\n      <SessionToken>kCpnd0w05JBlBJuyYpbdPXUUKmpoRc7P2AVQY9YZGZVAKRm5DDR8EqgtYjj7V0MBvp6Recfz4e1PDcOhUr/oaKuJFQIE/vn5WGq9cow/6shZMUw4U1VRNVhKUktRMDJC</SessionToken>\\n      <SenderNode>324</SenderNode>\\n      <SenderServer>%s</SenderServer>\\n      <SenderJournalNo>%s</SenderJournalNo>\\n      <SenderDate>%s</SenderDate>\\n      <SenderTime>%s</SenderTime>\\n      <TransferNode />\\n      <TransferServer />\\n      <TransferJournalNo />\\n      <TransferDate />\\n      <TransferTime />\\n    </SysReqHeader>\\n    <TxnReqHeader>\\n      <MessageType>0000</MessageType>\\n      <TransactionCode>%s</TransactionCode>\\n      <RelatedCycleNo>1</RelatedCycleNo>\\n      <RelatedAccDate>2023-03-29</RelatedAccDate>\\n    </TxnReqHeader>\\n  </RequestHeader>\\n  \\r\\n<RequestBody>\\n    <Custservice_Call>\\n \\r\\n<card_no>%s</card_no>\\n         \\r\\n<PIN-FLAG>%s</PIN-FLAG>\\n  \\r\\n<PWD>%s</PWD>\\n \\r\\n<COVERTTY>%s</COVERTTY>\\n \\r\\n</Custservice_Call>\\n  </RequestBody>\\n</hzbank>\",\n" +
                "  \"appCode\": \"CCFN3053\",\n" +
                "  \"type\": \"json\",\n" +
                "  \"toSys\": \"CARD02\"\n" +
                "}";
        String cmdurl = getCrdCommandUrl();

        log.info("yinShuCardNo:{}",cardNo);

        // 获取当前日期和时间
        LocalDateTime currentDateTime = LocalDateTime.now();
        // 定义占位符变量的值
        String transactionRef = currentDateTime.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")),
                senderServer = "CCRM",
                senderJournalNo = currentDateTime.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")),
                senderDate = currentDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
                senderTime = currentDateTime.format(DateTimeFormatter.ofPattern("HH:mm:ss")),
                transactionCode = "CCFN3053",
                //cardNo = cardNo,  //卡号（必填）
                pinFlag = "0",
                pwd = "0",
                covertty = "0";

        // 使用占位符变量替换 XML 字符串中的占位符
        requestBody = String.format(requestBody, transactionRef, senderServer, senderJournalNo, senderDate, senderTime,
                transactionCode, cardNo, pinFlag, pwd, covertty);

        cmdurl=cmdurl+"/Custservice_Call";

        CrdCmdResVo resVo=doCommond("CCFN3053",cmdurl,requestBody);
        return resVo.getMthsOdue();
    }

    /**
     * 银数已出&未出账账单明细DJKF0017（取未出账单）
     */
    public static CrdCmdResVo notOutBillDetailYs(String cardNo,String stmtDate)
    {//stmtDate = "202404";
        String cmdurl = getCrdCommandUrl();

        // 设置请求体
        String requestBody = "{\n" +
                "  \"body\": \"<?xml version=\\\"1.0\\\" encoding=\\\"GB18030\\\"?>\\n<hzbank xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xmlns:xsd=\\\"http://www.w3.org/2001/XMLSchema\\\" xmlns=\\\"http://www.hzbank.com.cn/ibservice/DJKF0017/\\\">\\n  <RequestHeader>\\n    <SysReqHeader>\\n      <TransactionRef>%s</TransactionRef>\\n      <BranchNo>7571</BranchNo>\\n      <SourceChannel>9998</SourceChannel>\\n      <Language>0001</Language>\\n      <VersionNo>1.1</VersionNo>\\n      <TerminalNo>8865473</TerminalNo>\\n      <SystemType>CO</SystemType>\\n      <OperatorId>310011</OperatorId>\\n      <SessionToken>kCpnd0w05JBlBJuyYpbdPXUUKmpoRc7P2AVQY9YZGZVAKRm5DDR8EqgtYjj7V0MBvp6Recfz4e1PDcOhUr/oaKuJFQIE/vn5WGq9cow/6shZMUw4U1VRNVhKUktRMDJC</SessionToken>\\n      <SenderNode>324</SenderNode>\\n      <SenderServer>%s</SenderServer>\\n      <SenderJournalNo>%s</SenderJournalNo>\\n      <SenderDate>%s</SenderDate>\\n      <SenderTime>%s</SenderTime>\\n      <TransferNode />\\n      <TransferServer />\\n      <TransferJournalNo />\\n      <TransferDate />\\n      <TransferTime />\\n    </SysReqHeader>\\n    <TxnReqHeader>\\n      <MessageType>0000</MessageType>\\n      <TransactionCode>%s</TransactionCode>\\n      <RelatedCycleNo>1</RelatedCycleNo>\\n      <RelatedAccDate>2023-03-29</RelatedAccDate>\\n    </TxnReqHeader>\\n  </RequestHeader>\\n  \\r\\n<RequestBody>\\n    <Bill_Business>\\n \\r\\n<card_no>%s</card_no>\\n         \\r\\n<stmt_date>%s</stmt_date>\\n \\r\\n<curr_cd></curr_cd>\\n \\r\\n<opt>%s</opt>\\n \\r\\n<user_flag></user_flag>\\n \\r\\n\\r\\n</Bill_Business>\\n  </RequestBody>\\n</hzbank>\",\n" +
                "  \"appCode\": \"DJKF0017\",\n" +
                "  \"type\": \"json\",\n" +
                "  \"toSys\": \"crd_serv\"\n" +
                "}";

        // 获取当前日期和时间
        LocalDateTime currentDateTime = LocalDateTime.now();
        if(JPubUtils.IsEmpty(stmtDate)){
            stmtDate=currentDateTime.format(DateTimeFormatter.ofPattern("yyyyMM"));
        }

        // 定义占位符变量的值
        String transactionRef = currentDateTime.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")),
                senderServer = "CCRM",
                senderJournalNo = currentDateTime.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")),
                senderDate = currentDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
                senderTime = currentDateTime.format(DateTimeFormatter.ofPattern("HH:mm:ss")),
                transactionCode = "DJKF0017";

        // 使用占位符变量替换 XML 字符串中的占位符
        requestBody = String.format(requestBody, transactionRef, senderServer, senderJournalNo,
                senderDate, senderTime,transactionCode,cardNo,stmtDate,"2");

        cmdurl=cmdurl+"/Bill_Business";

        return doCommond("DJKF0017",cmdurl,requestBody);
    }

    /**
     * 通联未出账账单明细DJKF0005
     */
    public static CrdCmdResVo notOutBillDetailTl(String cardNo)
    {
        String cmdurl = getCrdCommandUrl();

        // 设置请求体
        String requestBody = "{\n" +
                "  \"body\": \"<?xml version=\\\"1.0\\\" encoding=\\\"GB18030\\\"?>\\n<hzbank xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xmlns:xsd=\\\"http://www.w3.org/2001/XMLSchema\\\" xmlns=\\\"http://www.hzbank.com.cn/ibservice/DJKG0005/\\\">\\n  \\r\\n\\r\\n<RequestHeader>\\n    <SysReqHeader>\\n      <TransactionRef>%s</TransactionRef>\\n      <BranchNo>7571</BranchNo>\\n      <SourceChannel>9998</SourceChannel>\\n      <Language>0001</Language>\\n      <VersionNo>1.1</VersionNo>\\n \\r\\n\\r\\n     <TerminalNo>8865473</TerminalNo>\\n      <SystemType>CO</SystemType>\\n      <OperatorId>310011</OperatorId>\\n      \\r\\n\\r\\n<SessionToken>kCpnd0w05JBlBJuyYpbdPXUUKmpoRc7P2AVQY9YZGZVAKRm5DDR8EqgtYjj7V0MBvp6Recfz4e1PDcOhUr/oaKuJFQIE/vn5WGq9cow/6shZMUw4U1VRNVhKUktRMDJC</SessionToken>\\n      <SenderNode>324</SenderNode>\\n      <SenderServer>%s</SenderServer>\\n  \\r\\n\\r\\n    <SenderJournalNo>%s</SenderJournalNo>\\n      <SenderDate>%s</SenderDate>\\n      <SenderTime>%s</SenderTime>\\n      <TransferNode />\\n      <TransferServer />\\n      <TransferJournalNo />\\n      \\r\\n\\r\\n<TransferDate />\\n      <TransferTime />\\n    </SysReqHeader>\\n    <TxnReqHeader>\\n      <MessageType>0000</MessageType>\\n      <TransactionCode>%s</TransactionCode>\\n      <RelatedCycleNo>1</RelatedCycleNo>\\n      \\r\\n\\r\\n<RelatedAccDate>%s</RelatedAccDate>\\n    </TxnReqHeader>\\n  </RequestHeader>\\n  \\r\\n<RequestBody>\\n    <TransList_Business>\\n \\r\\n<card_no>%s</card_no>\\n         \\r\\n<curr_cd>%s</curr_cd>\\n \\r\\n<card_acct_sw></card_acct_sw>\\n \\r\\n<sett_txn_type></sett_txn_type>\\n \\r\\n<txn_amt1></txn_amt1>\\n \\r\\n<start_date></start_date>\\n\\r\\n<end_date></end_date>\\n\\r\\n<firstrow>%d</firstrow>\\n\\r\\n<lastrow>%d</lastrow>\\n\\r\\n<calc_total_amt_ind></calc_total_amt_ind>\\n\\r\\n<q_pin></q_pin>\\n\\r\\n<p_pin></p_pin>\\n\\r\\n<cust_id></cust_id>\\n\\r\\n<user_flag></user_flag>\\n\\r\\n</TransList_Business>\\n  </RequestBody>\\n</hzbank>\",\n" +
                "  \"appCode\": \"DJKG0005\",\n" +
                "  \"type\": \"json\",\n" +
                "  \"toSys\": \"crd_serv\"\n" +
                "}";

        // 获取当前日期和时间
        LocalDateTime currentDateTime = LocalDateTime.now();

        CrdCmdResVo cmdResVo=new CrdCmdResVo();
        // 定义占位符变量的值
        String transactionRef = currentDateTime.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")),
                senderServer = "CCRM",
                senderJournalNo = currentDateTime.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")),
                senderDate = currentDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
                senderTime = currentDateTime.format(DateTimeFormatter.ofPattern("HH:mm:ss")),
                transactionCode = "DJKG0005",
                relatedAccDate = currentDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
                currCd = "156";
        Integer firstRow = 0, lastRow = 9;
        String yetnextpageflg="Y";
        cmdurl = cmdurl + "/TransList_Business";
        List<CrdBillTailResVo> billTail=new ArrayList<>();
        while (JPubUtils.IsEqual(yetnextpageflg,"Y")) {
            // 使用占位符变量替换 XML 字符串中的占位符
            requestBody = String.format(requestBody, transactionRef, senderServer, senderJournalNo, senderDate, senderTime,
                    transactionCode, relatedAccDate, cardNo, currCd, firstRow, lastRow);
            CrdCmdResVo cmdResVoTem = doCommond("DJKG0005", cmdurl, requestBody);
            if(JPubUtils.IsEqual(cmdResVoTem.getRespCode(),"0")){ //2024-06-06
                billTail.addAll(cmdResVoTem.getBillTailList());
                yetnextpageflg = cmdResVoTem.getNextpageflg();
                log.info("notOutBillDetailTl.DJKG0005:{}", yetnextpageflg);
                firstRow += 10;
                lastRow += 10;
                if (firstRow > 100) {
                    log.warn("cardNo={}.DJKG0005 bill too many,break", cardNo);
                    break;
                }
            }
            else{
                log.warn("cardNo={}.DJKG0005 Commond.Fail", cardNo);
                break;
            }
        }

        cmdResVo.setBillTailList(billTail);

        return cmdResVo;
    }

    /**
     * 通联未入账账单明细DJKF0004
     */
    public static CrdCmdResVo notBillDetailTl(String cardNo)
    {
        String cmdurl = getCrdCommandUrl();

        // 设置请求体
        String requestBody = "{\n" +
                "  \"body\": \"<?xml version=\\\"1.0\\\" encoding=\\\"GB18030\\\"?>\\n<hzbank xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xmlns:xsd=\\\"http://www.w3.org/2001/XMLSchema\\\" xmlns=\\\"http://www.hzbank.com.cn/ibservice/DJKG0004/\\\">\\n  \\r\\n\\r\\n<RequestHeader>\\n    <SysReqHeader>\\n      <TransactionRef>%s</TransactionRef>\\n      <BranchNo>7571</BranchNo>\\n      <SourceChannel>9998</SourceChannel>\\n      <Language>0001</Language>\\n      <VersionNo>1.1</VersionNo>\\n \\r\\n\\r\\n     <TerminalNo>8865473</TerminalNo>\\n      <SystemType>CO</SystemType>\\n      <OperatorId>310011</OperatorId>\\n      \\r\\n\\r\\n<SessionToken>kCpnd0w05JBlBJuyYpbdPXUUKmpoRc7P2AVQY9YZGZVAKRm5DDR8EqgtYjj7V0MBvp6Recfz4e1PDcOhUr/oaKuJFQIE/vn5WGq9cow/6shZMUw4U1VRNVhKUktRMDJC</SessionToken>\\n      <SenderNode>324</SenderNode>\\n      <SenderServer>%s</SenderServer>\\n  \\r\\n\\r\\n    <SenderJournalNo>%s</SenderJournalNo>\\n      <SenderDate>%s</SenderDate>\\n      <SenderTime>%s</SenderTime>\\n      <TransferNode />\\n      <TransferServer />\\n      <TransferJournalNo />\\n      \\r\\n\\r\\n<TransferDate />\\n      <TransferTime />\\n    </SysReqHeader>\\n    <TxnReqHeader>\\n      <MessageType>0000</MessageType>\\n      <TransactionCode>%s</TransactionCode>\\n      <RelatedCycleNo>1</RelatedCycleNo>\\n      \\r\\n\\r\\n<RelatedAccDate>%s</RelatedAccDate>\\n    </TxnReqHeader>\\n  </RequestHeader>\\n  \\r\\n<RequestBody>\\n    <TransList_Business>\\n \\r\\n<card_no>%s</card_no>\\n         \\r\\n<curr_cd>%s</curr_cd>\\n \\r\\n</TransList_Business>\\n  </RequestBody>\\n</hzbank>\",\n" +
                "  \"appCode\": \"DJKG0004\",\n" +
                "  \"type\": \"json\",\n" +
                "  \"toSys\": \"crd_serv\"\n" +
                "}";

        // 获取当前日期和时间
        LocalDateTime currentDateTime = LocalDateTime.now();

        // 定义占位符变量的值
        String transactionRef = currentDateTime.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")),
                senderServer = "CCRM",
                senderJournalNo = currentDateTime.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")),
                senderDate = currentDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
                senderTime = currentDateTime.format(DateTimeFormatter.ofPattern("HH:mm:ss")),
                transactionCode = "DJKG0004",
                relatedAccDate = currentDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
                currCd = "156";

        // 使用占位符变量替换 XML 字符串中的占位符
        requestBody = String.format(requestBody, transactionRef, senderServer, senderJournalNo, senderDate, senderTime,
                transactionCode, relatedAccDate, cardNo, currCd);

        cmdurl=cmdurl+"/TransList_Business";

        return doCommond("DJKG0004",cmdurl,requestBody);
    }
}
